# -*- coding: utf-8 -*-

from rest_framework.generics import ListCreateAPIView
from rest_framework.permissions import IsAdminUser

from meiduo_admin.utils import PageNum
from users.models import User
from meiduo_admin.serializers.user import UserListSerializer, UserCreateSerializer


class UserView(ListCreateAPIView):
    """
    用户的查询获取
    """
    queryset = User.objects.all().order_by('id') # 不加排序的话，分页会报警告
    serializer_class = UserListSerializer
    pagination_class = PageNum

    permission_classes = [IsAdminUser]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return UserListSerializer
        else:
            return UserCreateSerializer
        pass

    def get_queryset(self):
        # 关键字
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return User.objects.all().order_by('id')
        else:
            return User.objects.filter(username=keyword).order_by('id')
